package com.dreamthen.controller;

import com.dreamthen.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zengms
 * @Date 2023-11-14 19:45:14
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(HttpServletRequest request) {

        Object loginName = request.getParameter("loginName");
        if (null == loginName || StringUtils.isEmpty(loginName)) {
            request.setAttribute("ex", "账号不能为空");
            return "error";
        }
        request.getSession().setAttribute("userName", loginName);
        //查数据
        //权限校验
        return "admin";
    }


    @GetMapping("/valid")
    public String valid() {
        return "valid";
    }

    @PostMapping("/valid")
    public String validUser(HttpServletRequest request, @Valid User user, BindingResult result) {
        System.out.println("****user=" + user);
        List<String> errorList = new ArrayList<>();
        if (result.hasErrors()) {
            for (FieldError fieldError : result.getFieldErrors()) {
                errorList.add(fieldError.getDefaultMessage());
            }
            request.setAttribute("ex", errorList);
            return "error";
        }
        return "admin";
    }

    @PostMapping("/valid2")
    @ResponseBody
    public Object validUser2(HttpServletRequest request, @Valid User user, BindingResult result) {
        System.out.println("****user=" + user);
        List<String> errorList = new ArrayList<>();
        if (result.hasErrors()) {
            for (FieldError fieldError : result.getFieldErrors()) {
                errorList.add(fieldError.getDefaultMessage());
            }
            request.setAttribute("ex", errorList);
            return errorList;
        }
        return "success";
    }

    @GetMapping("/valid3")
    public String validUser3(@Valid User user) {
        System.out.println("****valid3-user=" + user);
        return "admin";
    }
}
